package com.msgc.utils.crypto.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Random;

/**
 * @author liuyanming
 */
public class StringUtilsExt extends StringUtils {
	private static final String base = "abcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * byte数组转16进制字符串
     */
	public static String bytesToHexString(byte[] bytes){
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		StringBuilder stringBuilder = new StringBuilder();
		for (byte aByte : bytes) {
			int v = aByte & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}
    
    public static byte[] hexStringToBytes(String str) {
	    int len = str.length();
	    byte[] b = new byte[len / 2];
	    for (int i = 0; i < len; i += 2) {
	        b[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i + 1), 16));
	    }
	    return b;
	}

    
    /**
     * 生成随机字符串 
     */
    public static String random(int length) {
    	Random random = new Random();
    	StringBuilder sb = new StringBuilder();
    	for (int i = 0; i < length; i++) {
    		int number = random.nextInt(base.length());
    		sb.append(base.charAt(number));
    	}
    	return sb.toString();
    }
}
